package com.schillerchina.baselibrary.network.factory;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import retrofit2.Converter;

/**
 * @author zhangzhiguo
 * @date 2019-08-05 09:39
 * @Description: 网络请求GSON解析 产品类
 */

public class EncryptGsonRequestConverter<T>
        implements Converter<T, RequestBody>
{
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private final TypeAdapter<T> adapter;
    private final Gson gson;
    private static final String TAG = "BaseActivity";

    EncryptGsonRequestConverter(Gson gson, TypeAdapter<T> typeAdapter)
    {
        this.gson = gson;
        this.adapter = typeAdapter;
    }

    public RequestBody convert(T paramT)
            throws IOException
    {
        Buffer localBuffer = new Buffer();
        Object localObject = new OutputStreamWriter(localBuffer.outputStream(), UTF_8);
        localObject = this.gson.newJsonWriter((Writer)localObject);
        this.adapter.write((JsonWriter)localObject, paramT);
        ((JsonWriter)localObject).close();
        try
        {
            String request = localBuffer.readUtf8();
            return RequestBody.create(MEDIA_TYPE, request);
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        return null;
    }
}
